#!/usr/env/bin python
# -*- coding: utf-8 -*-

# @Time    : 2020/4/3 09:34
# @Author  : yangdy
# @Email   : yangdy@egu360.com
# @File    : 8.字符串转换整数 (atoi).2020-04-03.py
# @Software: PyCharm

__author__ = 'yangdy'


class Solution:
    def myAtoi(self, str: str) -> int:
        # import re
        # p = r'[+-]?\d+'
        # ans = re.match(p, str.strip(' '))
        # if not ans:
        #     return 0
        # str2 = ans.group()
        # si = -1 if '-' in str2 else 1
        # n = int(re.search(r'\d+', str2).group()) * si
        # maxn = (1 << 31) - 1
        # minn = -(1 << 31)
        # return n if n < maxn and n > minn else (maxn if n >= maxn else minn)
        num_str = str.strip()
        ll = len(num_str)
        if ll < 1:
            return 0
        inf = 2**31 - 1
        _inf = - (2**31)
        num = 0
        si = 1
        mm = {}
        for i in range(10):
            mm[f'{i}'] = i

        if num_str[0] == '-':
            si = -1
            i = 1
        elif num_str[0] == '+':
            i = 1
        else:
            i = 0
        while i < ll:
            if num_str[i] in mm:
                num = num * 10 + mm[num_str[i]]
            else:
                return si * num
            i += 1
            if num > inf:
                if si < 0:
                    return _inf
                return inf
        return si * num


solve = Solution()
s1 = "42"
print(s1, solve.myAtoi(s1))

s2 = "  -42"
print(s2, ':', solve.myAtoi(s2))

s3 = "4193 with words"
print(s3, ':', solve.myAtoi(s3))

s4 = "words and 987"
print(s4, ':', solve.myAtoi(s4))

s5 = "-91283472332"
print(s5, ':', solve.myAtoi(s5))

s6 = "2147483648"
print(s6, ':', solve.myAtoi(s6))
